package concurrency;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.SynchronousQueue;

/**
 * Created by sunzhengjie on 2017/1/20.
 */
public class TestBlockingQueue {

    static void getKey() {
        try {
            new BufferedReader(new InputStreamReader(System.in)).readLine();
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    static void getKey(String message) {
        System.out.println(message);
        getKey();
    }

    static void test(String msg, BlockingQueue<LiftOff> queue) {
        System.out.println(msg);
        LiftOffRunner runner = new LiftOffRunner(queue);
        Thread t = new Thread(runner);
        t.start();
        for (int i = 0; i < 5; i++) {
            runner.add(new LiftOff());
        }
        getKey("Press 'Enter' (" + msg + ")");
        t.interrupt();
        System.out.println("Finished " + msg + " test");
    }

    public static void main(String[] rar) {
        test("LinkedBlockingQueue", //unlimited size
                new LinkedBlockingDeque<LiftOff>());
  /*      test("ArrayBlockingQueue", //fixed size
                new ArrayBlockingQueue<LiftOff>(3));
        test("SynchronousQueue", //size 1
                new SynchronousQueue<LiftOff>());*/
    }

    static class LiftOffRunner implements Runnable {
        private BlockingQueue<LiftOff> rockets;

        public LiftOffRunner(BlockingQueue<LiftOff> queue) {
            this.rockets = queue;
        }

        public void add(LiftOff lo) {
            rockets.add(lo);
        }

        public void run() {
            try {
                while (!Thread.interrupted()) {
                    LiftOff rocket = rockets.take();
                    rocket.run();// use this thread
                }
            } catch (InterruptedException e) {
                System.out.println("Waling from take()");
            }
            System.out.println("Exiting LiftRunner");
        }
    }

    static class LiftOff implements Runnable {

        @Override
        public void run() {
            System.out.println("lift!");
        }
    }
}
